#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *threadRun(void *args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond, &mutex);
        cout << "我是线程：" << name << "我正在跑！" << endl;
        pthread_mutex_unlock(&mutex);
    }

    pthread_exit(nullptr);
}

int main()
{
    int num = 3;
    pthread_t parr[num];
    for(int i = 0; i < num; i++)
    {
        char* buff = new char(64);

        snprintf(buff, 64, "thread-%d ", i);
        pthread_create(parr + i, nullptr, threadRun, buff);
    }

    while(true)
    {
        //发出条件变量信号
        //pthread_cond_signal(&cond);
        pthread_cond_broadcast(&cond);
        //cout << "main signal" << endl;
        
        sleep(1);
    }

    //等待线程退出
    for(int i = 0; i < num; i++)
    {
        int ret = pthread_join(parr[i], nullptr);
        if(ret != 0) cout << "join error!" << endl;
    }

    return 0;
}